package com.nlp.visualization.service.tasks;

import com.google.gson.Gson;
import com.nlp.visualization.pojo.NLP.weibo.WeiboCSVEntity;
import com.nlp.visualization.pojo.NLP.weibo.WeiboContentEntity;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RecursiveAction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.nlp.visualization.common.CONSTANTS.TASK_MAX;

public class WeiboAnalyze2SQLTask extends RecursiveAction {
    Logger logger = LoggerFactory.getLogger(WeiboSeg2SQLTask.class);
    // 每个"小任务"最多只50个数
    private static final int MAX = TASK_MAX;

    private int start;
    private int end;
    private List<WeiboCSVEntity> lines;
    private ConcurrentLinkedQueue<String> queue;


    public WeiboAnalyze2SQLTask(int start, int end, List lines, ConcurrentLinkedQueue<String> queue) {
        this.start = start;
        this.end = end;
        this.lines = lines;
        this.queue = queue;


    }

    @Override
    protected void compute() {
        // 当end-start的值小于MAX时候，开始执行任务
        if ((end - start) < MAX) {
            for (int i = start; i < end; i++) {
                Gson gson = new Gson();
                //将文件读到的json转换成初始文件的实体
                WeiboCSVEntity csv = lines.get(i);
                //将微博的内容转成微博info的对象
                WeiboContentEntity weiboContent = gson.fromJson(csv.getWeibo_info().replaceAll("\\\\", ""), WeiboContentEntity.class);
                //判断是否是原创微博
                if (!weiboContent.isIs_reprint_weibo()) {
                    //插入原文本信息
                    queue.add(InsertContentSQL(csv, weiboContent));
                } else {
                    //不是原创微博，跳过本条记录
                    continue;
                }
            }
        } else {
            // 将大任务分解成两个小任务
            int middle = (start + end) / 2;
            WeiboAnalyze2SQLTask left = new WeiboAnalyze2SQLTask(start, middle, lines, queue);
            WeiboAnalyze2SQLTask right = new WeiboAnalyze2SQLTask(middle, end, lines, queue);
            // 并行执行两个小任务
            left.fork();
            right.fork();
        }
    }

    /**
     * 拼接sql字符串
     *
     * @param csv
     * @param weiboContent
     * @return
     */
    private String InsertContentSQL(WeiboCSVEntity csv, WeiboContentEntity weiboContent) {

        String content = filterEmoji(weiboContent.getWeibo_content().split("\u200B\u200B\u200B")[0]);
        content = content.replaceAll("'", "\\\\'");
        String weibo_id = csv.getWeibo_id();
        String user_id = csv.getUser_id();
        String theme = AnalyzeWeiboTheme(content);
        String keywords = AnalyzeWeiboKeywords(content);
        String time = getTime(weiboContent.getPublish_time());
        String SQL = "INSERT INTO T_WEIBO_THEME(USER_ID,WEIBO_ID,CONTENT,THEME,KEYWORDS,PUBLISH_TIME) VALUES(" +
                " '" + user_id + "','" + weibo_id + "','" + content + "','" + theme + "','" + keywords + "','" + time + "');";
        return SQL;

    }

    /**
     * 获取微博时间
     *
     * @param publish_time
     * @return
     */
    private String getTime(String publish_time) {

        publish_time = publish_time.replace("今天", "2017-10-19");
        Pattern pattern = Pattern.compile("[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}[ ][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}");
        Matcher matcher = pattern.matcher(publish_time);
        String dateStr = "";
        if (matcher.find()) {
            dateStr = matcher.group(0);
        }
        if (dateStr.equals("")) {
            pattern = Pattern.compile("[0-9]{1,2}月[0-9]{1,2}日[ ][0-9]{1,2}[:][0-9]{1,2}");
            matcher = pattern.matcher(publish_time);
            if (matcher.find()) {
                dateStr = matcher.group(0);
                dateStr = dateStr.replace("月", "-");
                dateStr = dateStr.replace("日", "");
                dateStr = "2017-" + dateStr + ":00";
            }

        }
        if (dateStr.equals(""))
            return "2017-10-19 00:00:00";
        return dateStr.toString();

    }

    /**
     * 根据微博内容，抽取微博关键字
     *
     * @param content
     * @return
     */
    private String AnalyzeWeiboKeywords(String content) {
        return "";
    }

    /**
     * 根据微博内容，抽取微博主题
     *
     * @param content
     * @return
     */
    private String AnalyzeWeiboTheme(String content) {

        return "";
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     *
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {
        if (StringUtils.isBlank(source)) {
            return source;
        }
        StringBuilder buf = null;
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (isEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }
                buf.append(codePoint);
            }
        }
        if (buf == null) {
            return source;
        } else {
            if (buf.length() == len) {
                buf = null;
                return source;
            } else {
                return buf.toString();
            }
        }
    }
}
